package com.qst.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.order.domain.DTO.UpdatePasswordDTO;
import com.qst.order.domain.Merchant;
import com.qst.order.domain.User;
import com.qst.order.mapper.MerchantMapper;
import com.qst.order.mapper.UserMapper;
import com.qst.order.service.UserService;
import com.qst.order.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    private final UserMapper userMapper;
    private final MerchantMapper merchantMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username",username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean findByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("phone",phone);
        return userMapper.selectOne(queryWrapper)!= null;
    }

    @Override
    @Transactional
    public boolean register(User user) {
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        int row = userMapper.insert(user);
        return  row>0;
    }

    @Override
    public Merchant getMerchantProfile(Integer merchantId) {
        return  merchantMapper.getMerchantProfile(merchantId);
    }

    @Override
    @Transactional
    public void updateMerchantProfile(Merchant merchant, Integer merchantId) {
        UpdateWrapper<Merchant> merchantUpdateWrapper = new UpdateWrapper<>();
        merchantUpdateWrapper.eq("merchant_id", merchantId)
                .set("shop_name", merchant.getShopName())
                .set("logo", merchant.getLogo())
                .set("`desc`", merchant.getDesc()).set("type", merchant.getType());

        merchantMapper.update(merchantUpdateWrapper);

        userMapper.update(new UpdateWrapper<User>().set("phone", merchant.getPhone()).eq("id", merchantId));

    }

    // 密码验证正则（字母+数字）
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[a-zA-Z])(?=.*\\d).+$");
    @Override
    @Transactional
    public Result<?> changePassword(String username, UpdatePasswordDTO dto) {
        // 1. 用MyBatis-Plus的条件构造器查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username); // 等价于 WHERE username = ?
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            return Result.error("用户不存在");
        }

        // 2. 验证原密码
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 3. 验证新密码格式
        if (!PASSWORD_PATTERN.matcher(dto.getNewPassword()).matches()) {
            return Result.error("新密码必须包含字母和数字");
        }

        // 4. 加密新密码并更新
        user.setPassword(passwordEncoder.encode(dto.getNewPassword()));
        userMapper.updateById(user); // MyBatis-Plus的更新方法（根据ID更新）

        return Result.success("密码修改成功");
    }
}
